package com.poetry.util;

import com.poetry.domain.dto.PoemDoc;
import com.poetry.domain.po.Author;
import com.poetry.domain.po.Poem;
import com.poetry.exception.SearchResult;
import com.poetry.mapper.AuthorMapper;
import com.poetry.mapper.PoemMapper;
import com.poetry.service.ISearchService;
import jakarta.annotation.Resource;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;

@Component
public class ToolsUtil {
    @Resource
    private ISearchService searchService;
    @Resource
    private PoemMapper poemMapper;
    @Resource
    private AuthorMapper authorMapper;

    @Tool(description = "诗词推荐、搜索、赏析、翻译")
    public String recommendPoetry(@ToolParam(description = "查询关键词")String query,
                                  @ToolParam(description = "查询类型（分别表示查询的诗词中作者、标题、内容中含有搜索关键词）：author、title、content",
                                          required = false) String type,
                                  @ToolParam(description = "查询作者关键词, 用于复合查询",
                                          required = false) String author) {
        List<Poem> list = getPoetry(query, type, author);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.toString();
    }

    @Tool(description = "诗词作者搜索、介绍")
    public String introduceAuthors(@ToolParam(description = "查询关键词")String query) {
        List<Author> list = getAuthors(query);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.toString();
    }

    private List<Poem> getPoetry(String query, String type, String author) {
        SearchResult<PoemDoc> searchPoems = searchService.searchPoems(query, type, null,  author,0, 4).getData();
        List<PoemDoc> poemDocs = searchPoems.content();
        if (poemDocs.isEmpty()) {
            return null;
        }
        List<Poem> poems = new ArrayList<>();
        for (PoemDoc poemDoc : poemDocs) {
            Poem poem = poemMapper.selectById(poemDoc.getId());
            poems.add(poem);
        }
        return poems;
    }

    private List<Author> getAuthors(String query) {
        List<Poem> poems = getPoetry(query, "author", query);
        if (poems == null || poems.isEmpty()) {
            return null;
        }
        List<Author> authors = new ArrayList<>();
        for (Poem poem : poems) {
            Author author = authorMapper.selectById(poem.getAuthorId());
            if (author != null && !authors.contains(author)) {
                authors.add(author);
            }
        }
        return authors;
    }
}

